package git.soulbgm.ting55;

import git.soulbgm.edu.piesat.EduPiesatApplication;
import git.soulbgm.utils.LogUtil;
import git.soulbgm.utils.PropertiesUtil;
import git.soulbgm.utils.okhttp.OkHttpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 程序入口
 *
 * @author SoulBGM
 * @date 2021/06/04
 */
public class Ting55Application {

    private static WebDriver driver;
    private static String baseUrl = "https://ting55.com";
    private static String menuUrl = baseUrl + "/book/13312";
    private final static LogUtil log = new LogUtil(Ting55Application.class);

    /**
     * 判断运行时是否是以jar运行
     *
     * @return boolean
     */
    private static boolean isJar(String path) {
        File file = new File(path);
        return file.isFile();
    }

    /**
     * 检测环境
     */
    private static void detectionEnvironment() throws IOException {
        String path = EduPiesatApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String configFilePath = "config.properties";
        if (isJar(path)) {
            path = path.substring(0, path.lastIndexOf(PropertiesUtil.LEFT_SLANTING_BAR));
            configFilePath = path + File.separator + "config.properties";
        }
        Map<String, String> config = PropertiesUtil.getPrefixProperties(configFilePath, "config", "#");
        System.setProperty("webdriver.chrome.driver", config.get("chromeDriverPath"));
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        detectionEnvironment();
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--mute-audio");
        chromeOptions.addArguments("--hide-scrollbars");
        driver = new ChromeDriver(chromeOptions);
        //driver.manage().window().maximize();
        driver.get(menuUrl);
        Document document = getDocument(driver);
        List<String> urlList = new ArrayList<>();
        Elements li = document.getElementsByClass("plist").last().getElementsByTag("ul").last().getElementsByTag("li");
        for (Element element : li) {
            String href = element.getElementsByTag("a").first().attr("href");
            String u = baseUrl + href;
            urlList.add(u);
        }
        CountDownLatch latch = new CountDownLatch(urlList.size());
        log.info("下载开始");
        for (int i = 0; i < urlList.size(); i++) {
            String url = urlList.get(i);
            driver.get(url);
            document = getDocument(driver);
            String mp3Url = document.getElementById("jp_audio_0").attr("src");
            if (mp3Url != null && !"".equals(mp3Url)) {
                String localPath = "E:\\BaiduNetdiskDownload\\屌丝道士-牛大宝\\" + (i + 1) + ".mp3";
                OkHttpUtil.downloadAsync(mp3Url, localPath, latch);
                log.info("获取地址{}", mp3Url);
            }
            Thread.sleep(1000 * 60 * 2);
        }
        try {
            latch.await();
            log.info("下载完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到文件
     *
     * @param driver 司机
     * @return {@link Document}
     */
    private static Document getDocument(WebDriver driver) {
        String htmlContent = driver.getPageSource();
        return Jsoup.parse(htmlContent);
    }

}
